package basic.study.leetcode;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName Mid49
 * @Description 字母异位词分组
 * @Company inspur
 * @Author Kevin
 * @Date 2020/6/22 15:48
 * @Version 1.0
 */
public class Mid49 {
    /**
     * 排序法
     */
    class Solution {
        HashMap<String, List<String>> res = new HashMap<>();
        public List<List<String>> groupAnagrams(String[] strs) {
            for (String s: strs) {
                char[] chars = s.toCharArray();
                Arrays.sort(chars);
                String key = String.valueOf(chars);
                if (!res.containsKey(key)) {
                    res.put(key, new ArrayList<>());
                }
                res.get(key).add(s);
            }
            return new ArrayList<>(res.values());
        }
    }

    /**
     * 计数法
     */
    class Solution1 {
        HashMap<String, List<String>> res = new HashMap<>();
        public List<List<String>> groupAnagrams(String[] strs) {
            int[] count = new int[26];
            for (String s: strs) {
                Arrays.fill(count, 0);
                char[] chars = s.toCharArray();
                for (char ch: chars) {
                    count[ch-'a']++;
                }

                StringBuilder sb = new StringBuilder();
                for (int c: count) {
                    sb.append('#');
                    sb.append(c);
                }
                String key = sb.toString();
                if (!res.containsKey(key)) {
                    res.put(key, new ArrayList<>());
                }
                res.get(key).add(s);
            }
            return new ArrayList<>(res.values());
        }
    }
}
